<?php
/**
 * 实体奖品扫码核销处理
 * Class CouponAfterScan
 */
namespace Scan;

use Model\ActivityMemberMod;
use Model\ActivityMemberTreasureMod;
use Model\AfterPersonMod;

class ExchangeScan extends Scan
{
    private $AfterPerson = null;   //活动员工核销
    private $ActivityMember = null;  //活动会员
    private $ActivityMemberTreasure = null;  //会员的奖品

    private $_exchange_number = 0;  //传过来的核销码
    private $_member = array();   //被核销的会员信息
    public function __construct()
    {
        global $_GPC;
        parent::__construct();
        $this->AfterPerson = new AfterPersonMod();
        $this->_exchange_number = $_GPC['number'];
    }

    public function index()
    {
        if(!$this->testUserAfterPerson()){
            return array('status'=>'error','err_msg'=>'操作失败，您不是核销员工');
        }
        if(!$this->testMemberAfterNumber()){
            return array('status'=>'error','err_msg'=>'核销失败，该用户核销码失效或者已经核销，请用户重新刷新页面！');
        }
        return $this->after();
    }

    /**
     * 检测当前用户是否为活动核销员
     */
    private function testUserAfterPerson()
    {
        return $this->AfterPerson->findOne(array('activity_id'=>$this->_activity_id,'uid'=>$this->_scan_uid,'status'=>1),array('id'));
    }

    /**
     * 验证用户的核销码
     */
    private function testMemberAfterNumber()
    {
        $this->ActivityMember = new ActivityMemberMod();
        $this->_member = $this->ActivityMember->findOne(array('activity_id'=>$this->_activity_id,'uid'=>$this->_dispose_uid,'exchange_number'=>$this->_exchange_number),array('id'));
        return $this->_member;
    }

    /**
     * 进行核销
     */
    private function after()
    {
        $this->ActivityMemberTreasure = new ActivityMemberTreasureMod();
        $_member_treasure = $this->ActivityMemberTreasure->findAll(array('activity_id'=>$this->_activity_id,'uid'=>$this->_dispose_uid,'type'=>2),array('order'=>array('id','desc')),array('id','exchange','number'));
        if(count($_member_treasure) > 0){
            $_is_after = false;  //是否已经核销
            foreach($_member_treasure as $_k=>$_v){
                if($_v['exchange'] < $_v['number']){
                    if(!$_is_after){
                        $_is_after = true;
                        $this->ActivityMember->update(array('exchange_number'=>mt_rand(100000,999999)),array('id'=>$this->_member['id']));
                    }
                    $this->ActivityMemberTreasure->update(array('exchange'=>$_v['number']),array('id'=>$_v['id']));
                }
            }
            if($_is_after){
                $this->_result = array('status'=>'success','success_msg'=>'核销成功');
            }else{
                $this->_result = array('status'=>'error','err_msg'=>'核销失败，该用户没有需要核销的奖品了');
            }
        }else{
            $this->_result = array('status'=>'error','err_msg'=>'核销失败，该用户没有需要核销的奖品了');
        }
        return $this->_result;
    }

}
